package handler

import (
	"car-rental-08-14/api/request"
	"car-rental-08-14/internal/dao"
	"car-rental-08-14/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddCar(c *gin.Context) {
	var req request.AddCarForm
	var car model.Car

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	car = model.Car{
		Title:        req.Title,
		Image:        req.Image,
		Price:        req.Price,
		PriceComment: req.PriceComment,
		Status:       req.Status,
	}

	err := car.AddCar()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "发布失败",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "发布成功",
		"data":    car,
	})
}

func ListCar(c *gin.Context) {
	var req request.ListCarForm
	var car []model.Car

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	err := dao.GetTableInfo(&model.Car{Status: req.Status}, &car)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "加载失败",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "展示成功",
		"data":    car,
	})
}

func UpdateCar(c *gin.Context) {
	var req request.UpdateCar
	var car model.Car

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "验证失败",
			"data":    "",
		})
		return
	}

	car = model.Car{
		Title:        req.Title,
		Image:        req.Image,
		Price:        req.Price,
		PriceComment: req.PriceComment,
		Status:       req.Status,
	}

	err := car.UpdatedCar()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "修改失败",
			"data":    "",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "修改成功",
		"data":    car,
	})
}
